import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import '/util/logger_util.dart';

/// <summary>
/// author：zwb
/// dateTime： 2022/1/18 16:51
/// filePath： lib/page_common/show_webview_page.dart
/// desc:
/// <summary>
///
class ShowWebviewPage extends StatefulWidget {
  final String url;
  final String title;
  const ShowWebviewPage({Key? key, this.url:'', this.title:''}) : super(key: key);

  @override
  _ShowWebviewPageState createState() => _ShowWebviewPageState();
}

class _ShowWebviewPageState extends State<ShowWebviewPage> {
  final flutterWebviewPlugin = new FlutterWebviewPlugin();
  bool hidden  = true;
// On urlChanged stream
  late StreamSubscription<WebViewStateChanged> _onStateChanged;
  late StreamSubscription<double> _onProgressChanged;
  // On destroy stream
  late StreamSubscription _onDestroy;
  String tag = 'webview_flutter';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _onStateChanged = flutterWebviewPlugin.onStateChanged.listen((event) {
      flutterWebviewPlugin.evalJavascript("window.document.title").then((title) {
        logger("window.document.title $title",tag: tag);
      });
    });
    _onProgressChanged = flutterWebviewPlugin.onProgressChanged.listen((double progress) {
      logger("progress -> $progress",tag: tag);
    });
    _onDestroy = flutterWebviewPlugin.onDestroy.listen((_) {
      logger("Destroyed",tag: tag);
      setState(() {
        hidden = false;
      });
      if (mounted) {
        // Actions like show a info toast.
        ScaffoldMessenger.of(context) .showSnackBar(const SnackBar(content: Text('Webview Destroyed')));
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return WebviewScaffold(
      url: widget.url,
      appBar: new AppBar(
        title: Text('${widget.title}'),
      ),
      withZoom: true,
      withLocalStorage: true,
      hidden: false,
      withJavascript: true,
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _onDestroy.cancel();
    _onProgressChanged.cancel();
    _onStateChanged.cancel();
    flutterWebviewPlugin.close();
    flutterWebviewPlugin.dispose();
  }
}
